package org.zxt.web.context.handler.parser;

import org.zxt.web.context.WebContext;
import org.zxt.web.context.annotation.RequestParam;
import org.zxt.web.context.handler.ArgumentParser;
import org.zxt.web.nio.IHTTPSession;

import java.lang.reflect.Array;
import java.lang.reflect.Parameter;
import java.util.List;

public class RequestParamParser implements ArgumentParser {
    @Override
    public boolean support(Parameter p) {
        return p.getAnnotation(RequestParam.class) != null;
    }

    @Override
    public Object parse(Parameter p, WebContext webContext, IHTTPSession session) {
        RequestParam requestParam = p.getAnnotation(RequestParam.class);
        List<String> vals = session.getParameters().get(requestParam.value());
        if(p.getType().isAssignableFrom(Array.class)){
            return vals.toArray(new Object[]{});
        }
        if(vals!=null && !vals.isEmpty()){
            return vals.get(0);
        } else {
            return vals;
        }
    }
}
